/***************************************************************************
 *   Copyright (C) 2007 by les pandas rouges   *
 *   pouet@pouet   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/

#include "shaperecognizertool.h"
#include <QFileDialog>
#include <QMessageBox>
#include <QApplication>
#include <QMenuBar>
#include <QStatusBar>
#include <QTextStream>
#include <QDockWidget>


ShapeRecognizerTool::ShapeRecognizerTool():points(NULL), nbPoints(0), activePoint(0)
{
    this->createActions();
    this->createMenus();
    this->createToolBars();
    this->createStatusBar();
    this->createDisplay();
    this->setWindowTitle(QString("Poonya Shape Recognizer Tool"));
}

void ShapeRecognizerTool::open()
{
    QString fileName = QFileDialog::getOpenFileName(this);
    if (!fileName.isEmpty())
    {
        this->loadFile(fileName);
    }
}

void ShapeRecognizerTool::about()
{
    QMessageBox::about(this, tr("About Application"), tr("The Application is used to test several shape recognition algorithms. It is part of the <b>Poonya</b> project."));
}

void ShapeRecognizerTool::createActions()
{
    this->openAct = new QAction(QIcon(":/fileopen.xpm"), tr("&Open..."), this);
    this->openAct->setShortcut(tr("Ctrl+O"));
    this-> openAct->setStatusTip(tr("Open an existing file"));
    connect(openAct, SIGNAL(triggered()), this, SLOT(open()));

    this->exitAct = new QAction(tr("E&xit"), this);
    this->exitAct->setShortcut(tr("Ctrl+Q"));
    this->exitAct->setStatusTip(tr("Exit the application"));
    connect(exitAct, SIGNAL(triggered()), this, SLOT(close()));

    this->aboutAct = new QAction(tr("&About"), this);
    this->aboutAct->setStatusTip(tr("Show the application's About box"));
    connect(aboutAct, SIGNAL(triggered()), this, SLOT(about()));

    this->aboutQtAct = new QAction(tr("About &Qt"), this);
    this->aboutQtAct->setStatusTip(tr("Show the Qt library's About box"));
    connect(aboutQtAct, SIGNAL(triggered()), qApp, SLOT(aboutQt()));

    this->nextPointAct = new QAction(tr("&Next Point"), this);
    this->nextPointAct->setStatusTip(tr("Select the next point"));
    this->nextPointAct->setShortcut(tr("N"));
    connect(nextPointAct, SIGNAL(triggered()), this, SLOT(nextPoint()));

    this->prevPointAct = new QAction(tr("&Previous Point"), this);
    this->prevPointAct->setStatusTip(tr("Select the previous point"));
    this->prevPointAct->setShortcut(tr("P"));
    connect(prevPointAct, SIGNAL(triggered()), this, SLOT(prevPoint()));
}

void ShapeRecognizerTool::createMenus()
{
    this->fileMenu = menuBar()->addMenu(tr("&File"));
    this->fileMenu->addAction(openAct);
    this->fileMenu->addSeparator();
    this->fileMenu->addAction(exitAct);

    this->menuBar()->addSeparator();

    this->helpMenu = menuBar()->addMenu(tr("&Help"));
    this->helpMenu->addAction(aboutAct);
    this->helpMenu->addAction(aboutQtAct);
}

void ShapeRecognizerTool::createToolBars()
{
    this->fileToolBar = addToolBar(tr("File"));
    this->fileToolBar->addAction(this->openAct);
    this->fileToolBar->addAction(this->nextPointAct);
    this->fileToolBar->addAction(this->prevPointAct);
}

void ShapeRecognizerTool::createStatusBar()
{
    this->statusBar()->showMessage(tr("Ready"));
    this->statusBar()->addPermanentWidget(&this->pointInfo);
}

void ShapeRecognizerTool::loadFile(const QString &fileName)
{
    this->closeFile();
    QFile file(fileName);
    if (!file.open(QFile::ReadOnly | QFile::Text))
    {
        QMessageBox::warning(this, tr("Application"), tr("Cannot read file %1:\n%2.").arg(fileName).arg(file.errorString()));
        return;
    }

    QTextStream in(&file);
    QApplication::setOverrideCursor(Qt::WaitCursor);
    this->nbPoints = 0;
    //first we count how many lines are in the file
    QString line;
    while (!in.atEnd())
    {
        line=in.readLine(75);
        if (!line.isEmpty())
        {
            this->nbPoints ++;
        }
    }
    //then we create the array of points
    bool fileValid = false;
    if (this->nbPoints>0)
    {
        fileValid = true;
        quint16 pointIndex = 0;
        in.seek(0);
        this->points = new MyIntPoint[nbPoints];
        while (!in.atEnd() && fileValid)
        {
            line=in.readLine(75);
            if (!line.isEmpty())
            {
                QStringList lineSplit = line.split(" ", QString::SkipEmptyParts);
                if (lineSplit.size()==2)
                {
                    bool ok;
                    points[pointIndex].setX(lineSplit.at(0).toInt(&ok));
                    fileValid = ok;
                    points[pointIndex].setY(lineSplit.at(1).toInt(&ok));
                    fileValid = fileValid && ok;
                }
                else
                {
                    fileValid = false;
                }
                pointIndex++;
            }
        }

    }
    if (fileValid)
    {
        this->activePoint = 0;
        this->statusBar()->showMessage(tr("File loaded"), 2000);
        this->dispMana.drawPath(this->points, this->nbPoints);
        this->dispMana.setActivePoint(0);
	this->updatePointInfo();
    }
    else
    {
        this->statusBar()->showMessage(tr("Error, file not loaded"), 2000);
        this->closeFile();
    }
    QApplication::restoreOverrideCursor();
}

void ShapeRecognizerTool::closeFile()
{
    this->nbPoints = 0;
    if (this->points != NULL)
    {
        delete[] this->points;
    }
}

ShapeRecognizerTool::~ShapeRecognizerTool()
{
    if (this->points != NULL)
    {
        delete this->points;
    }
}


void ShapeRecognizerTool::createDisplay()
{
    this->setCentralWidget(this->dispMana.getView());
    QDockWidget* scrollbarWid = new QDockWidget(this);
    scrollbarWid->setAllowedAreas(Qt::TopDockWidgetArea
                                  | Qt::BottomDockWidgetArea);
    scrollbarWid->setFeatures(QDockWidget::DockWidgetMovable);
    this->addDockWidget(Qt::TopDockWidgetArea, scrollbarWid);
    scrollbarWid->setWidget(this->dispMana.getSlider());
}

void ShapeRecognizerTool::nextPoint()
{
    if(this->activePoint<this->nbPoints-1)
    {
        this->activePoint++;
        this->dispMana.setActivePoint(this->activePoint);
        this->updatePointInfo();
    }
}
void ShapeRecognizerTool::prevPoint()
{
    if(this->activePoint>0)
    {
        this->activePoint--;
        this->dispMana.setActivePoint(this->activePoint);
	this->updatePointInfo();
    }
}

void ShapeRecognizerTool::updatePointInfo()
{
	this->pointInfo.setText(tr("point %1 x=%2 y=%3").arg(this->activePoint).arg(this->points[this->activePoint].x()).arg(this->points[this->activePoint].y()));
}
